//正则比对工具
exports.sign = sign;
exports.compare = compare;


/*
@params {object} regObj
{
  "Expression":"〖HT3.*?〗(.*?)〖HT〗",
  "Global":false,
  "IgnoreCase":false,
  "Multiline":false,
  "Replacement":"$1"
  "Target":1
}
@params {string} text
*/
function compare(regObj, text) {
  var results = [];
  if (!regObj && !regObj.Expression) {
    return results;
  }
  var attrs = '';
  attrs += regObj.Global ? 'g' : '';
  attrs += regObj.IgnoreCase ? 'i' : '';
  attrs += regObj.Multiline ? 'm' : '';
  var reg = new RegExp(regObj.Expression, attrs);
  var r;
  while (r = reg.exec(text)) {
    var tmp = r[0];
    var loc = [r.index, r[0].length];
    if (regObj.Target > 0) {
      var tar = r[regObj.Target];
      var start = tmp.indexOf(tar);
      loc = [loc[0] + start, tar.length];
      tmp = tar;
    }
    if (regObj.Replacement) {
      var tmpReg = new RegExp(regObj.Expression, attrs);
      tmp = tmp.replace(tmpReg, regObj.Replacement);
    }
    results.push({
      Location: loc,
      Text: tmp
    })

    /**
     * 如果非全局模式，一次后直接退出
     */
    if (!regObj.Global)
      break;
  }
  return results;
}


// function compare(reg, text, once) {
//   var result = [];
//   if (!reg) {
//     return result;
//   }
//   var res;
//   if (once) {
//     reg = new RegExp(reg.Expression);
//     res = reg.exec(text);
//     if (res){
//       var loc = [res.index,res[0].length];
//       result.push(loc);
//     }
//   } else {
//     reg = new RegExp(reg.Expression, 'g');
//     while (res = reg.exec(text)) {
//       var loc = [res.index,res[0].length];
//       result.push(loc);
//     }
//   }
//   return result;
// }

function sign() {
  var texts = arguments;
  var total = '';
  var list = [];
  for (var index in texts) {
    var text = texts[index];
    if (typeof text == 'string') {
      text = text.replace(/(\(|\)|\[|\]|\\|\*|\^|\$|\+|\?|\|)/g, '\\$1');
      var reg = /〖.*?〗/g;
      var result = reg.exec(text);
      if (result !== null) {
        var res;
        while (res = reg.exec(text)) {
          result += '.*?' + res[0];
        }
        list.push(result);
      }
    }
  }
  total = list.join('.*?');
  // if(total){
  //   return '/'+total+'/';
  // }
  return total;
}
